//
//  JobSetUpViewController.m
//  MagicZhao
//
//  Created by hy002 on 2017/12/13.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "JobSetUpViewController.h"
#import "Helper.h"
#import "TimeModel.h"
#import "SetUpTimeViewController.h"
#import "SetUpTimeModel.h"
#import "FreeDatesModel.h"
static NSString * CellIdentifier = @"homeCell";
@interface JobSetUpViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIButton *allCloseBtn;
    UIView *lineDview;
}
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UILabel *yearLab;
@property (nonatomic, strong)UILabel *monthLab;
@property (nonatomic, assign)NSInteger year;
@property (nonatomic, assign)NSInteger month;
@property (nonatomic, assign)NSInteger firstYear;
@property (nonatomic, assign)NSInteger firstMonth;
@property (nonatomic, strong)NSArray *nameAry;
@property (nonatomic, strong)NSMutableArray *dayAry;
@property (nonatomic, strong)NSMutableDictionary *closeDayDic;
@property (nonatomic, strong)NSString *todayStr;
@property (nonatomic, strong)NSMutableDictionary *allCloseDayDic;
@property (nonatomic, strong)NSMutableArray *allHavedayAry;

@end

@implementation JobSetUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dayAry = [NSMutableArray arrayWithCapacity:0];
    _allHavedayAry = [NSMutableArray arrayWithCapacity:0];
    _closeDayDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _allCloseDayDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _nameAry = @[@"一",@"二",@"三",@"四",@"五",@"六",@"日"];
    if (_haveTimeAry.count > 0)
    {
        for (SetUpTimeModel *model in _haveTimeAry)
        {
            NSArray *monthDayAry = model.freeDates;
            for (FreeDatesModel *dateModel in monthDayAry)
            {
                [_allHavedayAry addObject:dateModel.freeDate];
            }
        }
    }
   
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = @"工作设置";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(soureTimeAction)];
    rightBtn.tintColor = [UIColor whiteColor];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
//    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextAction)];
//    rightBarBtn.tintColor = [UIColor whiteColor];
//    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; //初始化格式器。
    [formatter setDateFormat:@"YYYY-MM-dd"];//定义时间为这种格式： YYYY-MM-dd hh:mm:ss 。
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    _todayStr = currentTime;
    NSArray *timeAry = [currentTime componentsSeparatedByString:@"-"];
    _year = [timeAry[0] integerValue];
    _firstYear = _year;
    _month = [timeAry[1] integerValue];
    _firstMonth = _month;
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40*displaywidth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    UIImageView *yearImgView = [ZCControl createImageViewWithFrame:CGRectMake(10*displaywidth, 7.5*displaywidth, 100*displaywidth, 25*displaywidth) ImageName:@"xuankuang-2"];
    [topView addSubview:yearImgView];
    self.yearLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, 70*displaywidth, 25*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%ld年",_year] Color:RGB(128, 128, 128)];
    _yearLab.textAlignment = NSTextAlignmentCenter;
    [yearImgView addSubview:_yearLab];
    UIButton *lastYearBtn = [ZCControl createButtonWithFrame:CGRectMake(-10, 0, 35*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(lastYearAction) Title:nil Font:12.0];
    lastYearBtn.backgroundColor = [UIColor clearColor];
    [yearImgView addSubview:lastYearBtn];
    UIButton *nextYearBtn = [ZCControl createButtonWithFrame:CGRectMake(75*displaywidth, 0, 35*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(nextYearAction) Title:nil Font:12.0];
    nextYearBtn.backgroundColor = [UIColor clearColor];
    [yearImgView addSubview:nextYearBtn];
    UIImageView *monthImgView = [ZCControl createImageViewWithFrame:CGRectMake(150*displaywidth, 7.5*displaywidth, 100*displaywidth, 25*displaywidth) ImageName:@"xuankuang"];
    [topView addSubview:monthImgView];
    self.monthLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, 70*displaywidth, 25*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%ld月",_month] Color:RGB(128, 128, 128)];
    _monthLab.textAlignment = NSTextAlignmentCenter;
    [monthImgView addSubview:_monthLab];
    UIButton *lastMonthBtn = [ZCControl createButtonWithFrame:CGRectMake(-10, 0, 35*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(lastMonthAction) Title:nil Font:12.0];
    lastMonthBtn.backgroundColor = [UIColor clearColor];
    [monthImgView addSubview:lastMonthBtn];
    UIButton *nextMonthBtn = [ZCControl createButtonWithFrame:CGRectMake(75*displaywidth, 0, 35*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(nextMonthAction) Title:nil Font:12.0];
    nextMonthBtn.backgroundColor = [UIColor clearColor];
    [monthImgView addSubview:nextMonthBtn];
    
    allCloseBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-55*displaywidth, 5*displaywidth, 45*displaywidth, 30*displaywidth) ImageName:nil Target:self Action:@selector(allCloseAction:) Title:@"全选" Font:16.0];
    allCloseBtn.selected = NO;
    allCloseBtn.backgroundColor = [UIColor clearColor];
    [allCloseBtn setTitleColor:RGB(129, 148, 196) forState:UIControlStateNormal];
    [topView addSubview:allCloseBtn];
    
    UIView *lineAView = [[UIView alloc] initWithFrame:CGRectMake(0, 39*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
    lineAView.backgroundColor = LinesColor;
    [topView addSubview:lineAView];
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 40*displaywidth, SCREEN_WIDTH, 40*displaywidth*6) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
    [self getNewMonthAllDay:[NSDate date]];
    
//    UIButton *saveBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , SCREEN_HEIGHT-60*displaywidth-SCREER_HeiX-STA_NAV_HEIGHT, SCREEN_WIDTH-120*displaywidth, 40*displaywidth) ImageName:nil Target:self Action:@selector(soureTimeAction) Title:@"确定" Font:15.0];
//    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    saveBtn.backgroundColor = ThemeColor;
//    [saveBtn.layer setMasksToBounds:YES];
//    [saveBtn.layer setCornerRadius:5*displaywidth];
//    [self.view addSubview:saveBtn];
    

}

//下一步
- (void)soureTimeAction
{

    if (_closeDayDic.allKeys == 0)
    {
        [LTools showMBProgressWithText:@"请选择要设置的日期" addToView:self.view];
        return;
    }
    NSInteger num = 0;
    for (NSString *key in _closeDayDic)
    {
        NSArray *detail = _closeDayDic[key];
        num += detail.count;
    }
    if (num == 0)
    {
        [LTools showMBProgressWithText:@"请选择要设置的日期" addToView:self.view];
        return;
    }
    if (self.timeBlock != nil)
    {
        self.timeBlock(_closeDayDic);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return _nameAry.count;
    }
    return _dayAry.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
//    [cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    CGFloat W = SCREEN_WIDTH/7;
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.section == 0)
    {
        UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(0, 10*displaywidth, W, 30*displaywidth) Font:14.0 Text:_nameAry[indexPath.row] Color:RGB(77, 77, 77)];
        titLab.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:titLab];
        
    }
    else
    {
        if (_dayAry.count > 0)
        {
            TimeModel *model = _dayAry[indexPath.row];
            if ([model.day integerValue] > 0)
            {
                UILabel *dayLab = [ZCControl createLabelWithFrame:CGRectMake((W-30*displaywidth)/2, 5*displaywidth, 30*displaywidth, 30*displaywidth) Font:14.0 Text:model.day Color:RGB(77, 77, 77)];
                dayLab.textAlignment = NSTextAlignmentCenter;
                
                if ([_closeDayDic.allKeys containsObject:[NSString stringWithFormat:@"%@-%@",model.year,model.month]])
                {
                    NSArray *closeDayAry = [_closeDayDic objectForKey:[NSString stringWithFormat:@"%@-%@",model.year,model.month]];
                    if ([closeDayAry containsObject:model.subTime])
                    {
                        dayLab.layer.cornerRadius = 15*displaywidth;
                        dayLab.layer.masksToBounds = YES;
                        dayLab.textColor = [UIColor whiteColor];
                        dayLab.backgroundColor = RGB(228, 80, 76);
                    }
                }
                
                
                if (!model.isAfterday)
                {
                    dayLab.textColor = RGB(204, 204, 204);
                }
                [cell.contentView addSubview:dayLab];
            }
            if (model.isToday)
            {
                UIView *dianView = [[UIView alloc] initWithFrame:CGRectMake(W/2-1.5*displaywidth, 32*displaywidth, 3*displaywidth, 3*displaywidth)];
                dianView.backgroundColor = RGB(228, 80, 76);
                dianView.layer.cornerRadius = 1.5*displaywidth;
                dianView.layer.masksToBounds = YES;
                [cell.contentView addSubview: dianView];
            }
        }
    }
    
    return cell;
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH/7, 40*displaywidth);
}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //cell被电击后移动的动画
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
    TimeModel *model = _dayAry[indexPath.row];
    if (!model.isAfterday)
    {
        return;
    }
    if (model.isHave)
    {
        NSMutableArray *closeDayAry = [NSMutableArray arrayWithCapacity:0];
        if ([_closeDayDic.allKeys containsObject:[NSString stringWithFormat:@"%@-%@",model.year,model.month]])
        {
            NSArray *array = [_closeDayDic objectForKey:[NSString stringWithFormat:@"%@-%@",model.year,model.month]];
            [closeDayAry addObjectsFromArray:array];
        }
    
        if ([closeDayAry containsObject:model.subTime])
        {
            [closeDayAry removeObject:model.subTime];
            
        }
        else
        {
            [closeDayAry addObject:model.subTime];

        }
        if (closeDayAry.count != 0)
        {
            [_closeDayDic setObject:closeDayAry forKey:[NSString stringWithFormat:@"%@-%@",model.year,model.month]];
        }
        else
        {
            if ([_closeDayDic.allKeys containsObject:[NSString stringWithFormat:@"%@-%@",model.year,model.month]])
            {
                [_closeDayDic removeObjectForKey:[NSString stringWithFormat:@"%@-%@",model.year,model.month]];
            }
            

        }
        
    }
    [UIView performWithoutAnimation:^{
        [collectionView reloadItemsAtIndexPaths:@[indexPath]];
    }];
}

- (void)getNewMonthAllDay:(NSDate *)date
{
    NSUInteger firstDayOrdinalInWeek = [Helper firstDayOfMonthOrdinalNumberInWeek:date];
    NSUInteger days = [Helper totalDaysInMonth:date];
    NSUInteger todayOrdinalInMonth = [Helper todaysOrdinalInMonth:date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; //初始化格式器。
    [formatter setDateFormat:@"YYYY-MM-dd"];//定义时间为这种格式： YYYY-MM-dd hh:mm:ss 。
    NSString *currentTime = [formatter stringFromDate:date];
    NSArray *timeAry = [currentTime componentsSeparatedByString:@"-"];
    NSString *yearStr = timeAry[0];
    NSString *monthStr = timeAry[1];
    [_dayAry removeAllObjects];
    NSInteger numcount = days+firstDayOrdinalInWeek-2;
    if (firstDayOrdinalInWeek == 1)
    {
        numcount = days+6;
    }
    for (int i = 0; i < numcount; i++)
    {
        TimeModel *model = [[TimeModel alloc] init];
        model.year = yearStr;
        model.month = monthStr;
        NSInteger time = i-firstDayOrdinalInWeek+3;
        if (firstDayOrdinalInWeek == 1)
        {
            time = i-6+firstDayOrdinalInWeek;
        }
        model.day = [NSString stringWithFormat:@"%ld",time];
        model.subTime = [NSString stringWithFormat:@"%@-%@-%@",yearStr,monthStr,[NSString stringWithFormat:@"%02ld",time]];
        if (time > 0)
        {
            model.isHave = YES;
        }
        else
        {
            model.isHave = NO;
        }
        if ([model.subTime isEqualToString:_todayStr])
        {
            model.isToday = YES;
        }
        if (time >= todayOrdinalInMonth && time > 0)
        {
            model.isAfterday = YES;
        }
        if ([_allHavedayAry containsObject:model.subTime])
        {
            model.isAfterday = NO;
        }
        [_dayAry addObject:model];
    }
    NSInteger num = _dayAry.count/7;
    if (_dayAry.count%7 != 0)
    {
        num++;
    }
    num += 1;
    _collectionView.frame = CGRectMake(0, 40*displaywidth, SCREEN_WIDTH, num*40*displaywidth);
    
    [_collectionView reloadData];
    if (!lineDview)
    {
        lineDview = [[UIView alloc] initWithFrame:CGRectMake(0, 280*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineDview.backgroundColor = LinesColor;
        [self.view addSubview:lineDview];
    }
    
    lineDview.frame = CGRectMake(0, (num + 1)*40*displaywidth, SCREEN_WIDTH, 1*displaywidth);
    
}

- (void)reloadCalendar
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *timeStr = [NSString stringWithFormat:@"%ld-%02ld-10",_year,_month];
    NSDate *date = [formatter dateFromString:timeStr];
    [self getNewMonthAllDay:date];
    
}

- (void)lastYearAction
{
    if (_year == _firstYear)
    {
        return;
    }
    _year -= 1;
    if (_year == _firstYear && _month < _firstMonth)
    {
        _month = _firstMonth;
        _monthLab.text = [NSString stringWithFormat:@"%ld月",_month];

    }
    _yearLab.text = [NSString stringWithFormat:@"%ld年",_year];
    [self reloadCalendar];
    [self changeStust];
}

- (void)nextYearAction
{
    _year += 1;
    _yearLab.text = [NSString stringWithFormat:@"%ld年",_year];
    [self reloadCalendar];
    [self changeStust];


}

- (void)lastMonthAction
{
    if (_year == _firstYear && _month == _firstMonth)
    {
        return;
    }
    if (_month == 1)
    {
        if (_year > _firstYear)
        {
            _year--;
        }
        _month = 12;
    }
    else
    {
        _month -= 1;
    }
    
    _monthLab.text = [NSString stringWithFormat:@"%ld月",_month];
    _yearLab.text = [NSString stringWithFormat:@"%ld年",_year];
    [self reloadCalendar];
    [self changeStust];

}

- (void)nextMonthAction
{
    if (_month == 12)
    {
        _year++;
        _month = 1;
    }
    else
    {
        _month += 1;
    }
    _yearLab.text = [NSString stringWithFormat:@"%ld年",_year];
    _monthLab.text = [NSString stringWithFormat:@"%ld月",_month];
    [self reloadCalendar];
    [self changeStust];

}

//全选
- (void)allCloseAction:(UIButton *)btn
{
    if ([_allCloseDayDic.allKeys containsObject:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]])
    {
        NSString *str = [_allCloseDayDic objectForKey:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]];
        if ([str isEqualToString:@"0"])
        {
            str = @"1";
            btn.selected = YES;
        }
        else
        {
            str = @"0";
            btn.selected = NO;

        }
        [_allCloseDayDic setObject:str forKey:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]];
    }
    else
    {
         [_allCloseDayDic setObject:@"1" forKey:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]];
         btn.selected = YES;

    }
    if ([_closeDayDic.allKeys containsObject:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]])
    {
        [_closeDayDic removeObjectForKey:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]];
    }
    NSString *title = @"全选";
    if (btn.selected)
    {
        title = @"取消";
        NSMutableArray *closeDayAry = [NSMutableArray arrayWithCapacity:0];
        for (TimeModel *model in _dayAry)
        {
            if (model.isAfterday)
            {
                [closeDayAry addObject:model.subTime];
            }
        }
        [_closeDayDic setObject:closeDayAry forKey:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]];
    }
    [btn setTitle:title forState:UIControlStateNormal];
    [_collectionView reloadData];
}

- (void)changeStust
{
    if ([_allCloseDayDic.allKeys containsObject:[NSString stringWithFormat:@"%ld-%02ld",_year,_month]])
    {
        NSString *str = [_allCloseDayDic objectForKey:[NSString stringWithFormat:@"%ld-%ld",_year,_month]];
        if ([str isEqualToString:@"0"])
        {
            [allCloseBtn setTitle:@"全选" forState:UIControlStateNormal];
        }
        else
        {
            [allCloseBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    else
    {
        [allCloseBtn setTitle:@"全选" forState:UIControlStateNormal];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
